from flask import Blueprint, request, session
from flask_restful import Api, Resource, marshal_with
from flask_restful.reqparse import RequestParser

from webapp.config import api_utils
from webapp.config.api_utils import oper_log, check_auth
from webapp.dto_mapper import borrow_page_fields
from webapp.schema import BorrowSchema
from webapp.service.borrowinfo_service import BorrowInfoService

borrowinfo_app = Blueprint('borrowinfo', __name__, url_prefix='/api/borrowinfo')
borrowinfo_api = Api(borrowinfo_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)
parser.add_argument('resourceId', location='json', type=int, trim=False, required=False)
parser.add_argument('rtype', location='json', type=int, trim=False, required=False)
parser.add_argument('start', location='json', type=str, trim=False, required=False)
parser.add_argument('end', location='json', type=str, trim=False, required=False)
parser.add_argument('status', location='json', type=int, trim=False, required=False)


@borrowinfo_api.resource("", "/")
class BorrowInfoApi(Resource):
    @oper_log('查询所有借用资源信息', request)
    @check_auth('borrow:list', request)
    @marshal_with(borrow_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = api_utils.build_params(params)
        return BorrowInfoService.query_all(**params_dict)


    @oper_log('新增资源借用记录', request)
    @check_auth('borrow:add', request)
    def post(self):
        params = request.get_json()
        schema = BorrowSchema()
        curr_borrow = schema.load(params, unknown="exclude")
        user = session["user"]
        curr_borrow.create_by = user["username"]
        BorrowInfoService.create(curr_borrow=curr_borrow)

    @oper_log('删除借用记录', request)
    @check_auth('borrow:del', request)
    def delete(self):
        ids = request.get_json()
        borrow_set = set()
        for _id in ids:
            borrow_set.add(BorrowInfoService.find_by_id(id=_id))
        BorrowInfoService.delete(borrow_set=borrow_set)

    @oper_log('修改借用记录', request)
    @check_auth('borrow:edit', request)
    def put(self):
        # parser_put = parser.copy()
        # parser_put.parse_args()
        params = request.get_json()
        schema = BorrowSchema()
        curr_borrow = schema.load(params, unknown="exclude")
        user = session["user"]
        curr_borrow.update_by = user["username"]
        BorrowInfoService.update(curr_borrow=curr_borrow)